/**
 *
 */
package com.elcom.emocbc.cbm;

import java.io.IOException;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;

import com.elcom.emocbc.db.CellBroadcastDAO;
import com.elcom.emocbc.util.GeneratorSeq;
import com.elcom.emocbc.common.ipc.message.cbcmessage.BROADCAST_SUBMIT_ACK;

/**
 * @author tiamo114
 *
 */
public class BroadcastJob implements Job {

    private final Log LOG = LogFactory.getLog(BroadcastJob.class);
    private Scheduler schedule = null;
    private BroadcastDTO broadcast = null;
    private CellBroadcastDAO dao = null;

    /**
     *
     */
    public BroadcastJob() {
        dao = new CellBroadcastDAO();
    }

    /*
     * (non-Javadoc)
     *
     * @see org.quartz.Job#execute(org.quartz.JobExecutionContext)
     */
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        broadcast = BroadcastDTO.class.cast(context.getMergedJobDataMap().get("broadcast"));
        schedule = Scheduler.class.cast(context.getMergedJobDataMap().get("schedule"));
        String job_name = (String) context.getMergedJobDataMap().get("job_name");
        String job_group = (String) context.getMergedJobDataMap().get("job_group");

        List<MenuItemDTO> listMenu = dao.getListMenuItem(broadcast.getTopicID(), broadcast.getProgramID());
        String display = dao.getDisplayContent(broadcast.getProgramID());
        LOG.debug("Broadcasting subcontent: " + display);

        // Create an array containing the elements in a list
        MenuItemDTO[] menu = new MenuItemDTO[listMenu.size()];
        for (int i = 0; i < menu.length; i++) {
            menu[i] = listMenu.get(i);
        }

        try {
            int messageID = GeneratorSeq.getNextSeq();
            BROADCAST_SUBMIT_ACK rs = CellBroadcastService.generateCBMStructFile(menu, display, messageID, broadcast.getTopicID(), 0, broadcast.getZone(), broadcast.getStartTime(), broadcast.getBroadcastID());
            dao.insertBroadcastHist(broadcast, display, rs.getErrorCode());

            LOG.info("Finish broadcast for: " + broadcast.toString());
            dao.updateStateBroadcast(broadcast, CellBroadcastService.NORMAL);
            try {
                schedule.deleteJob(job_name, job_group);
            } catch (SchedulerException e) {
                LOG.error("", e);
            }
        } catch (IOException e) {
            LOG.error("", e);
        }

    }
}
